package com.upbos.sso;

import com.upbos.sso.entity.SsoUser;
import com.upbos.sso.entity.Token;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class UserContext {

    protected SsoManager ssoManager;

    protected HttpServletRequest request;

    public UserContext() {
        super();
    }

    public UserContext(SsoManager ssoManager, HttpServletRequest request) {
        this.ssoManager = ssoManager;
        this.request = request;
    }

    public SsoUser getSsoUser() {
        Token token = ssoManager.getToken(request);
        return token == null ? null : ssoManager.getSsoUser(token.getId());
    }

    public boolean hasRole(String key) {
        List<String> roles = getSsoUserRole();
        if (roles != null && roles.contains(key)) {
            return true;
        }
        return false;
    }

    public List<String> getSsoUserRole() {
        Token token = ssoManager.getToken(request);
        return token == null ? null : ssoManager.getAttr(token.getId(), Constants.SESSION_CACHE_ROLE_KEY_NAME);
    }

    public boolean hasPrivilege(String key) {
        List<String> privileges = getSsoUserPrivilege();
        if (privileges != null && privileges.contains(key)) {
            return true;
        }
        return false;
    }

    public List<String> getSsoUserPrivilege() {
        Token token = ssoManager.getToken(request);
        return token == null ? null : ssoManager.getAttr(token.getId(), Constants.SESSION_CACHE_PRIVILEGE);
    }

    public String getTokenId() {
        Token token = ssoManager.getToken(request);
        return token == null ? null : token.getId();
    }


    public void setAttr(String key, Object value) {
        ssoManager.setAttr(request, key, value);
    }


    public <T> T getAttr(String key) {
        return ssoManager.getAttr(request, key);
    }


    public void removeAttr(String key) {
        ssoManager.removeAttr(request, key);
    }

}
